<template>
  <div class="root">
    <audio id="audio" loop>
      <source src="@/assets/audio/warning.mp3" type="audio/mpeg">
    </audio>
    <!-- 顶部logo横幅 -->
    <div class="top-logo">
      <div class="weather" @click="goBack">
        <el-button type="primary" icon="el-icon-back" circle></el-button>
      </div>
      <div class="clock">{{ time }}</div>
    </div>
    <div class="container">
      <!-- 左侧 -->
      <div class="left-container calc-width">
        <div class="current-bus custom-border">
          <!-- <div class="green-dot title">本站公交</div> -->
          <div :style="{width: cardList.length * 160 + 20 + 'px' }">
            <div
              :class="index == active ? 'car-item avtive-car-item' : 'car-item'"
              v-for="(item, index) in cardList"
              :key="index"
              @click="itemClick(item, index)"
            >
              <img src="@/assets/images/bus.png" />
              <p style="font-size:14px" class="lin-code">{{ item.lineCode }} 路</p>
              <p class="car-id">{{ item.busName }}</p>
              <div class="green-dot">
                出发时间 {{ item.planBegin.substring(0, 2) }} :
                {{ item.planBegin.substring(2) }}
              </div>
              <div class="red-dot">
                到站时间 {{ item.planEnd.substring(0, 2) }} :
                {{ item.planEnd.substring(2) }}
              </div>
              <p class="lin-code">{{item.realDriver}}</p>

            </div>
          </div>
        </div>
        <!-- 上行 -->
        <div class="car-route">
          <div class="title">{{ allRoute.currentShift }}路(上行)</div>
          <img class="dot left" src="../../assets/images/green-dot.png" />
          <div class="route">
            <div class="car-item-box">
              <div
                class="car-item"
                :class="addClassName(item, 'up')"
                v-for="item in allRoute.stationListUp"
                :key="item.id">
                {{ item.statName }}
                <div class="service-icon" v-if="createIcon(item)"><!-- 服务网点图标 --></div>
                <template v-if="createIcon(item)">
                  <div class="service-station">
                  {{createIcon(item).name}}
                  </div>
                </template>
                <div v-if="createPackageMsg(item)" class="station-name">{{createPackageMsg(item)}}</div>
              </div>
            </div>
          </div>
          <img class="dot right" src="../../assets/images/red-dot.png" />
        </div>
        <!-- 下行 -->
        <div class="car-route">
          <div class="title">{{ allRoute.currentShift }}路(下行)</div>
          <img class="dot left" src="../../assets/images/red-dot.png" />
          <div class="route">
            <div class="car-item-box">
              <div
                class="car-item down car-down"
                :class="addClassName(item, 'down')"
                v-for="item in allRoute.stationListDown"
                :key="item.id"
              >
                {{ item.statName }}
                <div class="service-icon" v-if="createIcon(item)"><!-- 服务网点图标 --></div>
                <template v-if="createIcon(item)">
                  <div class="service-station">
                  {{createIcon(item).name}}
                  </div>
                </template>
                <div v-if="createPackageMsg(item)" class="station-name">
                  {{createPackageMsg(item)}}
                </div>
              </div>
            </div>
          </div>
          <img class="dot right" src="../../assets/images/green-dot.png" />
        </div>
      </div>
      <!-- 右侧 -->
      <div class="right-container">
        <div class="package custom-border warning">
          <p class="green-dot">到达预警信息</p>
          <div
            :class="index == 0 ? 'package-item active-package' : 'package-item'"
            class="package-item"
            v-for="(item, index) in packageList"
            :key="index">
            <img v-if="index == 0" src="../../assets/images/active-warning.png" />
            <img v-else src="../../assets/images/warning.png" />
            <div>
              您的{{item.package}}正在运输中, 预计将于<span>{{ parseTime(item.arrive_time,'{h}:{i}') }}</span>
              到达<span>{{item.staioin_name}}</span>站,当前距离{{item.staioin_name}}站约<span>{{parseInt(item.distance/1000)}}km</span>请提前准备查收
            </div>
          </div>
        </div>
        <div class="package custom-border">
          <p class="green-dot">包裹信息</p>
          <div class="parcel-table-box">
            <el-table a :data="parcelTableData"   :header-cell-class-name="headerStyle" :cell-class-name="tableCellStyle" :row-class-name="tableCellStyle" height="calc(100vh - 555px)">
              <el-table-column prop="packageCode" show-overflow-tooltip label="单号"></el-table-column>
              <el-table-column prop="packageWeight" label="重量" width="70"></el-table-column>
              <el-table-column prop="packageSize" label="数量" width="70"></el-table-column>
              <el-table-column prop="packageType" label="格口号" width="70"></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getBusByCurr,
  getBusStationByCurr,
  getBusPositionByCurr,
  listMyPackage,
  configKey,
  khystation
} from "@/api/station";
export default {
  data() {
    return {
      time: this.parseTime(new Date()),
      cardList: [],
      //选择的路线
      allRoute: {
        currentBus: 0,
      },
      scrollWidth: "1200",
      active: 0,
      visible: true,
      //关注的站点
      followStation: this.$store.state.user.station?this.$store.state.user.station.split(","):null,
      //包裹信息
      packageList: [],
      //查询参数
      query: {},
      parcelTableData:[],
      //播报间隔时间
      broadcastTime:180,
      //服务网点
      serviceStation:[]
    };
  },
  created() {
    configKey().then(res=>{
      if(res.code == 200 ) {
        this.broadcastTime = res.msg
      }
      this.getBusByCurr();
    }).catch(err => {
      this.getBusByCurr();
    })
    this.tasks();
    //右上角时间
    this.intervalId = setInterval(() => {
      this.time = this.parseTime(new Date());
    }, 1000);
    //服务站点
    this.khystation()
  },
  destroyed() {
    clearInterval(this.timerId);
    clearInterval(this.intervalId);
  },
  methods: {
    //服务站点
    khystation(){
      khystation().then(res=>{
        this.serviceStation = res.data
      })
    },
    //获取包裹信息
    listPackage() {
      listMyPackage(this.query.id).then(res => {
        this.parcelTableData = res.rows
      })
    },
    //获取当前用户站点的所有车辆信息
    getBusByCurr() {
      getBusByCurr().then((res) => {
        this.cardList = res.data;
        if(this.query.id){
          const index  = res.data.findIndex( item => item.id == this.query.id)
          //找到了 不需要刷新路线 只需要刷新车辆信息
          if(index != -1){
            this.active = index
            this.query = res.data[index]
            this.getBusPositionByCurr(res.data[index]);
          }
          //当前排班已下班
          if( index == -1 && res.data.length > 0 ){
            this.query = res.data[index]
            this.active = 0
            this.getStations(res.data[0]);
            this.listPackage()
          }
        }
        if( !this.query.id && res.data.length > 0){
          this.query = res.data[0]
          this.getStations(res.data[0]);
          this.listPackage()
        }
      });
    },
    //获取当前车辆的经过的站点信息
    getStations(item) {
      getBusStationByCurr(item.id).then((res) => {
        this.allRoute = {
          //currentBus: "", //当前公交所在站点
          currentShift: item.lineCode, //公交路线
          stationListUp: res.data.up.reverse(), //当前路线站点信息 => 上行
          stationListDown: res.data.down.reverse(), //当前路线站点信息 => 下行
        };
        this.getBusPositionByCurr(item);
      });
    },
    //获取当前车辆距离距离关注站点的状态信息
    getBusPositionByCurr(item) {
      getBusPositionByCurr(item.id, this.allRoute.currentBus?this.allRoute.currentBus:'').then((res) => {
        const data = res.data.busPotison;
        //当前车子所在站点
        this.allRoute.currentBus = data ? JSON.parse(data).goStationCode : "";
        //车辆运行偏离轨迹
        if(this.allRoute.currentBus){
          const stations = [...this.allRoute.stationListUp,...this.allRoute.stationListDown]
          const item = stations.find( item => item.id == this.allRoute.currentBus)
          if(item == undefined){
            this.$modal.msgWarning('当前车辆偏离排班路线，无法展示车辆位置信息！')
          }
        }
        // 包裹信息
        this.packageList = this.getPackageList(res.data);
        //如果包裹信息中有小于三分钟到达目的地车辆就播报一下
        this.broadcast(this.packageList)
      }).catch(err=>{
        this.allRoute.currentBus = ""
        this.packageList = []
      })
    },
    //格式化包裹信息 => 转为list
    getPackageList(data) {
      delete data.busPotison;
      delete data.remark;
      let list = [];
      for (const key in data) {
        if(data[key].busCalcu){
          list.push(JSON.parse(data[key].busCalcu));
        }
      }
      return list;
    },
    //语音播报
    broadcast( list ){
      const item = list.find( item => item.duration < parseInt(this.broadcastTime) )
      if(item){
        document.getElementById('audio').play()
        this.$notify({
          title: '警告',
          message: '您有一个包裹即将到站，请提前做好准备',
          type: 'warning',
          duration: 58000,
          onClose(){
            document.getElementById('audio').pause()
          }
        });
      }
    },
    //根据数据添加class
    addClassName(item, direction) {
      let className = ''
      if (this.followStation.includes(String(item.id))) {
        className += "active-station "; //本站
      }
      if (item.id == this.allRoute.currentBus && direction == "up"){
        className += "active-car-up "; //车子上行
      }
      if (item.id == this.allRoute.currentBus && direction == "down") {
        className += "active-car-down "; //车子下行
      }
      return className
    },
    //生成包裹信息
    createPackageMsg( { id } ){
      const item = this.packageList.find((item) => item.id == id)
      if(item){
        return `${this.query.busName}，预计${this.parseTime(item.arrive_time,'{h}:{i}')}到达`
      }
      return ''
    },
    //生成服务网点图标
    createIcon({id}){
     return this.serviceStation.find(item =>{
        const ids = item.stationId.split(',')
        return ids.includes(String(id))
      })
    },
    //选择班次
    itemClick(item, index) {
      if (index == this.active) return;
      this.active = index;
      this.query = item;
      this.allRoute.currentBus = ''
      this.getStations(item);
      this.listPackage()
    },
    //定时任务
    tasks() {
        this.timerId = setInterval(() => {
          this.getBusByCurr()
        }, 60000);
    },
    //返回
    goBack() {
      history.back();
    },
        /** table头部样式 */
    headerStyle({row, column, rowIndex, columnIndex}) {
      return 'tableStyle'
    },
    /** table行样式 */
    tableCellStyle ({row, column, rowIndex, columnIndex}) {
      return 'cellStyle'
    },
  },
};
</script>
<style lang="scss" scoped>
::-webkit-scrollbar-thumb {
    background-color: #d57b25;
}
.root {
  min-width: 1369px;
  height: 100vh;
  color: #fff;
  background-color: #010720;
  overflow: hidden;

  .top-logo {
    height: 75px;
    font-size: 16px;
    background: url(../../assets/images/top-logo.png),
    linear-gradient(0deg, #010824 1%, #010824 99%);
    background-size: 100% 100%;
    background-repeat: no-repeat;

    .weather {
      float: left;
      margin-top: 15px;
      margin-left: 155px;
    }
    .clock {
      float: right;
      margin-top: 25px;
      margin-right: 155px;

      &::before {
        content: "";
        display: inline-block;
        width: 16px;
        height: 16px;
        background-image: url(../../assets/images/clock.png);
        background-size: 100% 100%;
        vertical-align: top;
        margin-right: 10px;
        margin-top: 1px;
      }
    }
  }

  .container {
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    background-color: #010824;

    .custom-border {
      background-image: url(../../assets/images/border.png);
      background-size: 100% 100%;
    }
    .calc-width {
      width: calc(100% - 360px - 20px);
    }

    .green-dot::before {
      content: "";
      display: inline-block;
      width: 4px;
      height: 4px;
      border-radius: 2px;
      background-color: #41ad8c;
      margin-bottom: 3px;
      margin-right: 8px;
    }
    .red-dot::before {
      content: "";
      display: inline-block;
      width: 4px;
      height: 4px;
      border-radius: 2px;
      background-color: #c0050d;
      margin-bottom: 3px;
      margin-right: 8px;
    }

    .left-container {
      margin-top: 20px;

      .current-bus {
        font-size: 12px;
        height: 170px;
        overflow-x: hidden;

        &:hover {
          overflow-x: auto;
        }

        .title {
          font-size: 14px;
          margin-left: 20px;
        }
        .lin-code {
          margin: 2px;
        }
        .car-id {
          margin: 0;
          font-size: 14px;
        }

        .car-item {
          position: relative;
          float: left;
          width: 140px;
          height: 140px;
          text-align: center;
          margin-top: 15px;
          margin-left: 20px;
          opacity: 0.8;
          background-color: #021353;

          div {
            line-height: 22px;
          }

          img {
            width: 28px;
            height: 15px;
            margin-top: 10px;
          }
        }
        .avtive-car-item {
          background-color: #022087;
          border: 1px solid #007cff;
          box-shadow: 0 5px 20px 0 #000000;
          opacity: 1;
        }
      }
      .car-route {
        position: relative;
        height: calc((100vh - 305px) / 2);
        margin-top: 10px;
        border-radius: 2px;
        background-color: #001969;

        .dot {
          position: absolute;
          top: 90px;
          width: 20px;
          height: 20px;
          vertical-align: middle;
          z-index: 9;
          transform: scale(1.2);
        }

        .left {
          left: 25px;
        }

        .right {
          right: 25px;
        }

        .title {
          padding-left: 20px;
          height: 32px;
          line-height: 30px;
          font-size: 14px;
          border-bottom: 1px solid #11307e;
        }
      }

      .route {
        position: absolute;
        width: calc(100% - 59px);
        height: 10px;
        top: 95px;
        left: 30px;
        background: #3959e2;
        border-radius: 4px;

        .car-item-box {
          position: absolute;
          padding-top: 30px;
          top: -27px;
          display: flex;
          justify-content: space-between;
          font-size: 14px;
          width: 100%;
          padding-bottom: 18px;

          .service-icon{
            position: absolute;
            width: 30px;
            height: 35px;
            top: -37px;
            left: -10px;
            background-image: url(../../assets/images/station-icon.png);
            background-size: 100%;
            background-repeat: no-repeat;
          }

          .car-item {
            position: relative;
            width: 12px;
            font-size: 13px;

            .service-station {
              position: absolute;
              top: -66px;
              width: 78px;
              left: -20px;
              color: #91ff79;
            }
            .station-name {
              position: absolute;
              padding: 4px 4px;
              top: -47px;
              transform: translate(-35%);
              border-radius: 4px;
              color: #fff;
              white-space: nowrap;
              font-size: 12px;
              background-color: #ed7200;
              &::before {
                content: "";
                position: absolute;
                bottom: -3px;
                left: 35.5%;
                width: 6px;
                height: 6px;
                transform: rotate(45deg);
                background-color: #ed7200;
                border-radius: 2px;
              }
            }

            &:last-child {
              margin-right: 0;
            }

            &::before {
              content: "";
              display: inline-block;
              width: 4px;
              height: 4px;
              margin-left: 2px;
              margin-bottom: 12px;
              border-top: 1px solid #fff;
              border-right: 1px solid #fff;
              transform: rotate(45deg);
            }
          }

          .down {
            &::before {
              transform: rotate(225deg);
            }
          }

          .active-station {
            position: relative;
            &::after {
              content: "";
              position: absolute;
              top: -19px;
              left: -11px;
              width: 30px;
              height: 35px;
              background-image: url(../../assets/images/current-station.png);
              background-size: cover;
              transform: scale(.8)
            }
          }

          .active-car-up {
            position: relative;
            &::before {
              content: "";
              display: block;
              margin-top: -8px;
              margin-left: -10px;
              width: 31px;
              height: 20px;
              margin-bottom: 8px;
              background-image: url(../../assets/images/to-right.png);
              background-size: cover;
              transform: rotate(0);
              border: none;
            }
          }

          .active-car-down {
            position: relative;
            &::before {
              content: "";
              display: block;
              margin-top: -8px;
              margin-left: -10px;
              width: 31px;
              height: 20px;
              margin-bottom: 8px;
              background-image: url(../../assets/images/to-left.png);
              background-size: cover;
              transform: rotate(0);
              border: none;
            }
          }
        }
      }
    }
    .right-container {
      width: 360px;
      margin-top: 20px;



      .package {
        font-size: 18px;
        padding: 10px 15px 15px;
        background-image: url(../../assets/images/bg_car.png);

        p {
          margin-top: 0;
          margin-bottom: 15px;
        }

        .package-item {
          display: flex;
          min-height: 92px;
          padding: 0 14px;
          margin-top: 8px;
          align-items: center;
          font-size: 14px;
          word-break: break-all;
          color: #7096de;
          text-align: justify;
          box-shadow: inset 0 0 23px 0 rgba(0, 83, 170, 0.71);
          border-radius: 4px;
          img {
            width: 48px;
            height: 48px;
            margin-right: 10px;
          }
        }
         span {
            color: #d57b25;
          }
        .active-package {
          box-shadow: inset 0 0 23px 0 #ff8c07;
        }
      }
      .warning{
        height: 360px;
        margin-bottom: 12px;
        overflow-y: auto;
      }
    }
  }
}
      .parcel-table-box {
        .el-table {
          background: transparent;
          &::before {
            background-color: transparent;
          }
          ::v-deep .el-table__cell.gutter {
            display: none !important;
          }
        }

        ::v-deep .tableStyle {
          background-image: linear-gradient(179deg, #003091 0%, rgba(0,17,107,0.90) 100%);
          color: #fff;
          border-bottom: 0 !important;
        }

        ::v-deep .cellStyle {
          border-bottom: 0!important;
          background: transparent!important;
          color: #b7cdf6;
          cursor: pointer;
        }
      }
</style>
